﻿using MiniFox.Components;
using MiniFox.Infrastructure;
using MiniFox.Platform.Models;
using MiniFox.Platform.Providers;
using MiniFox.Utility;

namespace OAuth2.Data
{
    [AutoResolve]
    public class TicketProvider : BaseOAuth2DataProvider, ITicketProvider
    {
        public void DisableTicket(Ticket ticket)
        {
            var sys_ticket = this.CurrentDbContext.SysTicket.SingleOrDefault(t => t.TicketId == ticket.TicketID);
            if (sys_ticket == null)
            {
                return;
            }

            this.Delete(sys_ticket);
        }

        public T GetTicketData<T>(Ticket ticket, TicketType ticketType) where T : class 
        {
            var sys_ticket = this.CurrentDbContext.SysTicket.SingleOrDefault(t => t.TicketId == ticket.TicketID && t.TicketType == ticketType.ToString());
            if (sys_ticket == null)
            {
                return null;
            }
            return sys_ticket.Data.ToJsonObject<T>();
        }

        public bool SetTicketData<T>(Ticket ticket, TicketType ticketType, T data) where T : class
        {
            var sys_ticket = this.CurrentDbContext.SysTicket.SingleOrDefault(t => t.TicketId == ticket.TicketID && t.TicketType == ticketType.ToString());
            if (sys_ticket == null)
            {
                sys_ticket = new()
                {
                    TicketId = ticket.TicketID,
                    CreateTime = ticket.CreationTime.DateTime,
                    ExpireTime = ticket.ExpiredTime.DateTime,
                    IsVerified = false,
                    TicketType = ticketType.ToString(),
                    Data = data.ToJsonString()
                };
                return this.Insert(sys_ticket) > 0;
            }
            else
            {
                sys_ticket.TicketId = ticket.TicketID;
                sys_ticket.CreateTime = ticket.CreationTime.DateTime;
                sys_ticket.ExpireTime = ticket.ExpiredTime.DateTime;
                sys_ticket.IsVerified = false;
                sys_ticket.TicketType = ticketType.ToString();
                sys_ticket.Data = data.ToJsonString();

                return this.Update(sys_ticket) > 0;
            }

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ticket"></param>
        public void VerifyTicket(Ticket ticket)
        {
            var sys_ticket = this.CurrentDbContext.SysTicket.SingleOrDefault(t => t.TicketId == ticket.TicketID);
            if (sys_ticket == null)
                return;

            sys_ticket.IsVerified  = true;
            this.Update(sys_ticket);
        }
    }
}
